package com.meals.system.service.impl;

import com.meals.system.api.user.param.SystemUserUpdateParam;
import com.meals.system.common.Constants;
import com.meals.system.common.ServiceResultEnum;
import com.meals.system.common.SystemException;
import com.meals.system.dao.SystemUserMapper;
import com.meals.system.dao.SystemUserTokenMapper;
import com.meals.system.entity.SystemUser;
import com.meals.system.entity.SystemUserToken;
import com.meals.system.service.WhitesMealUserService;
import com.meals.system.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * Description:
 * Parm:
 * return:
 * Author: Chen
 * Date: 2021/12/5
 */
@Service
public class WhitesMealUserServiceImpl implements WhitesMealUserService{

    @Autowired
    private SystemUserMapper systemUserMapper;
    @Autowired
    private SystemUserTokenMapper systemUserTokenMapper;

    @Override
    public String register(String loginName, String password){
        if(systemUserMapper.selectByLoginName(loginName) != null){
            return ServiceResultEnum.SAME_LOGIN_NAME_EXIST.getResult();
        }
        SystemUser registerUser = new SystemUser();
        registerUser.setLoginName(loginName);
        registerUser.setNickName(loginName);
        registerUser.setIntroduceSign(Constants.USER_INTRO);
        String passwordMD5 = MD5Util.MD5Encode(password,"UTF-8");
        registerUser.setPasswordMd5(passwordMD5);
        System.out.println("registerUser" + registerUser);
        if(systemUserMapper.insertSelective(registerUser) > 0){
            return ServiceResultEnum.SUCCESS.getResult();
        }
        return ServiceResultEnum.DB_ERROR.getResult();
    }

    @Override
    public String login(String loginName, String passwordMD5){
        SystemUser user = systemUserMapper.selectByLoginNameAndPassword(loginName, passwordMD5);
        if (user != null){
            if (user.getLockedFlag() == 1){
                return ServiceResultEnum.LOGIN_USER_LOCKED_ERROR.getResult();
            }
            // 登录后即执行token的操作
            String token = getNewToken(System.currentTimeMillis() + "", user.getUserId());
            SystemUserToken systemUserToken = systemUserTokenMapper.selectByPrimaryKey(user.getUserId());
            // 当前时间
            Date now = new Date();
            // 过期时间
            Date expireTime = new Date(now.getTime() + 2 * 24 * 3600 * 1000);//过期时间 48小时
            if (systemUserToken == null){
                systemUserToken = new SystemUserToken();
                systemUserToken.setUserId(user.getUserId());
                systemUserToken.setToken(token);
                systemUserToken.setUpdateTime(now);
                systemUserToken.setExpireTime(expireTime);
                // 新增一条token数据
                if (systemUserTokenMapper.insertSelective(systemUserToken)>0){
                    return token;
                }
            }
        }
        return ServiceResultEnum.LOGIN_ERROR.getResult();
    }

    /**
     * 获取token值
     * @param timeStr
     * @param userId
     * @return
     */
   private String getNewToken(String timeStr, Long userId){
        String src = timeStr + userId + NumberUtil.genRandomNum(4);
        return SystemUtil.genToken(src);
   }

   @Override
    public Boolean updateUserInfo(SystemUserUpdateParam systemUser, Long userId){
       // 找到id对应的user
       SystemUser user = systemUserMapper.selectByPrimaryKey(userId);
       if (user == null){
           SystemException.fail(ServiceResultEnum.DATA_NOT_EXIST.getResult());
       }
       user.setNickName(systemUser.getNickName());
       // user.setPasswordMd5(mallUser.getPasswordMd5());
       // 若密码为空字符，则表明用户不打算修改密码，使用原密码保存
       if (!MD5Util.MD5Encode("","UTF-8").equals(systemUser.getPasswordMd5())){
           user.setPasswordMd5(systemUser.getPasswordMd5());
       }
       user.setIntroduceSign(systemUser.getIntroduceSign());
       if (systemUserMapper.updateByPrimaryKeySelective(user) > 0){
           return true;
       }
       return false;
   }

   @Override
    public Boolean logout(Long userId){
       return systemUserTokenMapper.deleteByPrimaryKey(userId) > 0;
   }

   @Override
    public PageResult getWhitesMealUsersPage(PageQueryUtil pageUtil){
       List<SystemUser> systemUsers = systemUserMapper.findSystemUserList(pageUtil);
       int total = systemUserMapper.getTotalSystemUser(pageUtil);
       PageResult pageResult = new PageResult(systemUsers,total,pageUtil.getLimit(),pageUtil.getPage());
        return pageResult;
   }

   @Override
    public Boolean lockUsers(Long[] ids, int lockStatus){
       if (ids.length < 1){
           return false;
       }
       return systemUserMapper.lockUserBatch(ids,lockStatus) > 0;
   }

}
